from django.shortcuts import render
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http import HttpResponse
from rest_framework.generics import GenericAPIView
from .serializers import RegisterSMSCodeSerializer
from rest_framework.response import Response
from rest_framework import status
from random import randint
from libs.yuntongxun.sms import CCP

# Create your views here.

class RegisterCodeImageView(APIView):
    """
    获取验证码

    GET:/verifications/imagecodes/(?P<image_code_id>.+)/
    """

    def get(self,request,image_code_id):
        """
        思路：

        通过第三方生成图片验证码
        通过redis将验证码信息保存
        返回图片
        """
        # 通过第三方生成图片验证码
        text,image = captcha.generate_captcha()
        # 通过redis将验证码信息保存
        redis_conn = get_redis_connection('code')
        #记录
        redis_conn.setex('img_%s'%image_code_id,60,text)
        # 返回图片
        return HttpResponse(image,content_type='image/jpeg')


class RegisterSMSCodeView(GenericAPIView):
    """
    根据用户提交的验证码进行校验
    GET /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx
    """

    serializer_class = RegisterSMSCodeSerializer

    def get(self,request,mobile):
        """
        思路

        校验 text
        连接redis，判断是否是否发送过
        生成短信验证码
        通过redis记录验证码和发送状态
        发送短信验证码
        """
        # 校验text
        serializer = RegisterSMSCodeSerializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        # 连接redis，判断是否是否发送过
        redis_conn = get_redis_connection('code')

        flag = redis_conn.get('sms_flag_%s'%mobile)
        if flag:
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)
        # 生成短信验证码
        sms_code = '%06d'%randint(0,999999)
        # 通过redis记录验证码和发送状态
        # redis_conn.setex('sms_%s'%mobile,60*5,sms_code)
        # redis_conn.setex('sms_flag_%s'%mobile,60,1)
        #通过管道实现一次提交
        pl = redis_conn.pipeline()
        pl.setex('sms_%s'%mobile,60*5,sms_code)
        pl.setex('sms_flag_%s'%mobile,60,1)
        pl.execute()

        # 发送短信验证码
        # ccp = CCP()
        # ccp.send_template_sms(mobile,[sms_code,5],1)

        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)

        return Response({'message':'ok'})




